package com.org.redis.lru;

import com.org.redis.config.JedisClient;
import com.org.redis.config.JedisUtils;
import redis.clients.jedis.Jedis;

import java.util.List;
import java.util.UUID;

/**
 * 使用redis实现LRU栈
 * @author wang
 */
public class LRURedisStack {

    /**
     * 默认LRU缓存长度为8
     */
    static final int DEFAULT_SIZE = 16;

    /**
     * 最多的LRU缓存长度
     */
    static final int MAX_SIZE = 1 << 30;

    /**
     *
     */
    static final String LRU_STACK_NAME = "lru_stack_";

    /**
     * 缓存长度
     */
    private int capacity;

    /**
     * 默认key
     */
    private String key;


    /**
     * jedis client
     */
    private Jedis jedis = JedisUtils.getJedis();


    /**
     * 计数器
     */
    private int count;

    public LRURedisStack(){
        this(DEFAULT_SIZE, "");
    }

    public LRURedisStack(int capacity){
        this(capacity,"");
    }

    public LRURedisStack(String key){
        this(DEFAULT_SIZE,key);
    }

    public LRURedisStack(int capacity, String key){
        if(capacity >= MAX_SIZE){
            this.capacity = MAX_SIZE;
        }else {
            this.capacity = capacity;
        }
        if ("".equals(key)){
            this.key = LRU_STACK_NAME + JedisClient.incr(key);
        }else {
            this.key = key;
        }
        while (jedis.exists(key)){
            key = UUID.randomUUID().toString().replaceAll("-","");
        }

    }

    public void add(String value){
        if( (jedis.llen(key) + 1) > this.capacity){
            jedis.rpop(key);
        }
        jedis.lpush(this.key,value);
        count++;
    }

    public String get(int site){
        List<String> list = jedis.lrange(key, site-1, site-1);
        return list.get(0);
    }

    public List<String> getAll(){
        return jedis.lrange( key, 0, -1 );
    }

    public int size(){
        return jedis.llen(key).intValue();
    }

    public boolean containsValue(String value){
        List<String> list = getAll();
        for (String s : list){
            if(value.equals(s)){
                return true;
            }
        }
        return false;
    }

    public void clear(){
        jedis.ltrim(key,1,0);
    }

    public void removeValue(String value){
        jedis.lrem(key,1,value);
    }

}
